import { ControlBase } from './controlbase';
import { Injectable } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';


@Injectable()
export class DynamicFormService {
    constructor(
        private fb: FormBuilder
    ) { }

    toFormGroup(controls: ControlBase<any>[]) {
        let group: any = {};
        //兼容自由变化的行列
        controls.forEach((ctrl: any) => {
            if (ctrl.length) {
                ctrl.forEach(c => {
                    group[c.key] = [c.value, c.validators];
                    // group[c.key] = new FormControl(ctrl.value, c.validators);
                    // group[c.key] = ctrl.required ? new FormControl(ctrl.value || '', Validators.required)
                    //     : new FormControl(ctrl.value || '');
                });
            } else {
                group[ctrl.key] = [ctrl.value, ctrl.validators];
                // group[ctrl.key] = new FormControl(ctrl.value, ctrl.validators);
                // group[ctrl.key] = ctrl.required ? new FormControl(ctrl.value || '', Validators.required)
                //     : new FormControl(ctrl.value || '');

            }
        });
        // controls.forEach(ctrl => {
        //     group[ctrl.key] = ctrl.required ? new FormControl(ctrl.value || '', Validators.required)
        //         : new FormControl(ctrl.value || '');

        // });
        // return new FormGroup(group);
        return this.fb.group(group);
    }
}
